<template>
  <view class="container">
    <uni-card>
      <!-- 充电站信息 -->
      <view class="station-info">
        <view class="station-header">
          <image src="../../static/charging-station.png" class="station-icon"></image>
          <text class="station-name">{{stationInfo.name}}</text>
          <text class="station-status" :class="{'available': stationInfo.status === 1}">
            {{stationInfo.status === 1 ? '空闲中' : '忙碌中'}}
          </text>
        </view>
        <view class="station-detail">
          <text class="station-address">{{stationInfo.address}}</text>
          <text class="station-distance">{{stationInfo.distance}}km</text>
        </view>
      </view>

      <!-- 环形进度条 -->
      <view class="progress-wrapper">
        <view class="progress-circle">
          <view class="progress-background"></view>
          <view class="progress-fill" :style="fillStyle"></view>
          <text class="progress-percent">{{progress}}%</text>
        </view>
      </view>

      <!-- 充电信息卡片 -->
      <view class="info-card">
        <view class="info-row">
          <text class="info-label">充电桩编号</text>
          <text class="info-value">{{chargingInfo.deviceNo}}</text>
        </view>
        <view class="info-row">
          <text class="info-label">充电模式</text>
          <text class="info-value">{{chargingInfo.mode}}</text>
        </view>
        <view class="info-row">
          <text class="info-label">开始时间</text>
          <text class="info-value">{{chargingInfo.startTime}}</text>
        </view>
      </view>

      <!-- 充电统计信息 -->
      <view class="stats-grid">
        <view class="stat-item">
          <text class="stat-value">{{chargingProgress.oneElectricityCost}}元</text>
          <text class="stat-label">当前电价</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{formatTime}}</text>
          <text class="stat-label">充电时长</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{chargingProgress.chargingCapacity}}kWh</text>
          <text class="stat-label">已充电量</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{chargingProgress.totalCost.toFixed(2)}}元</text>
          <text class="stat-label">充电金额</text>
        </view>
      </view>

      <!-- 充电曲线图 -->
      <view class="chart-container">
        <text class="section-title">充电功率曲线</text>
        <canvas canvas-id="powerChart" class="chart"></canvas>
      </view>
    </uni-card>

    <!-- 操作按钮组 -->
    <view class="action-buttons">
      <button class="action-btn extend-btn" @tap="extendCharging">
        <image src="../../static/extend.png" class="btn-icon"></image>
        <text>延长充电</text>
      </button>
      <button class="action-btn stop-btn" @tap="stopCharging">
        <image src="../../static/stop.png" class="btn-icon"></image>
        <text>结束充电</text>
      </button>
      <button class="action-btn help-btn" @tap="showHelp">
        <image src="../../static/help.png" class="btn-icon"></image>
        <text>使用帮助</text>
      </button>
    </view>

    <!-- 通知弹窗 -->
    <uni-popup ref="alertDialog" type="dialog">
      <uni-popup-dialog 
        :type="msgType" 
        cancelText="关闭" 
        confirmText="确定" 
        title="系统通知" 
        :content="messageText"
        @confirm="dialogConfirm" 
        @close="dialogClose">
      </uni-popup-dialog>
    </uni-popup>

    <!-- 延长充电弹窗 -->
    <uni-popup ref="extendDialog" type="dialog">
      <view class="extend-dialog">
        <text class="dialog-title">延长充电时间</text>
        <picker mode="selector" :range="extendOptions" @change="onExtendChange">
          <view class="picker">
            选择延长时间：{{extendOptions[extendIndex]}}
          </view>
        </picker>
        <view class="dialog-buttons">
          <button class="dialog-btn cancel" @tap="cancelExtend">取消</button>
          <button class="dialog-btn confirm" @tap="confirmExtend">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
		// 充电站信息
		      stationInfo: {
		        name: "XX充电站-A区",
		        status: 1,
		        address: "XX市XX区XX路123号",
		        distance: 1.5
		      },
		      
		      // 充电信息
		      chargingInfo: {
		        deviceNo: "CZ-2023-0086",
		        mode: "快充",
		        startTime: this.formatDateTime(new Date())
		      },
		      
		      // 延长充电选项
		      extendOptions: ["30分钟", "1小时", "2小时", "自定义"],
		      extendIndex: 0,
      // 充电进度数据
      chargingProgress: {
        chargingCapacity: 0,     // 已充电量（千瓦时）
        totalCapacity: 1,        // 总电量（初始设为1避免除0）
        oneElectricityCost: 0,   // 电价（元/度）
        hours: 0,                // 充电小时数
        minutes: 0,              // 充电分钟数
        seconds: 0,              // 充电秒数
        totalCost: 0             // 总费用（元）
      },
      
      // WebSocket相关
      socketTask: null,
      pingInterval: null,
      isSocketConnected: false,
      
      // 弹窗相关
      msgType: "",               // 消息类型：success/warning/error/info
      messageText: "",           // 消息内容
      
      // 页面状态
      billId: "",                // 订单ID
      userId: "",                // 用户ID
      isPageShow: false,         // 页面是否显示
      startTime: null,           // 充电开始时间
      
      // 其他状态
      isCharging: false,         // 是否正在充电
      timer: null,               // 计时器
      reconnectCount: 0          // WebSocket重连次数
    }
  },
  computed: {
    // 计算充电百分比（0.0-100.0）
    progress() {
      const percent = (this.chargingProgress.chargingCapacity / this.chargingProgress.totalCapacity) * 100;
      return Math.min(100, Math.max(0, percent)).toFixed(1);
    },
    
    // 进度条填充样式
    fillStyle() {
      const deg = this.progress * 3.6; // 将百分比转为角度
      return {
        transform: `rotate(${deg}deg)`,
        clipPath: this.progress <= 50 ? 'inset(0 50% 0 0)' : 'inset(0)'
      };
    },
    
    // 格式化时间显示
    formatTime() {
      const pad = num => num.toString().padStart(2, '0');
      return `${pad(this.chargingProgress.hours)}:${pad(this.chargingProgress.minutes)}:${pad(this.chargingProgress.seconds)}`;
    }
  },
  onLoad(options) {
    this.billId = options.billId || "";
    this.userId = uni.getStorageSync("userId") || "";
    this.startTime = new Date();
  },
  onShow() {
    this.isPageShow = true;
    if (!this.isSocketConnected) {
      this.initWebSocket();
    }
  },
  onHide() {
    this.isPageShow = false;
    this.closeWebSocket();
  },
  onUnload() {
    this.cleanup();
  },
  methods: {
	  // 格式化日期时间
	      formatDateTime(date) {
	        const pad = num => num.toString().padStart(2, '0');
	        return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
	      },
	      
	      // 延长充电
	      extendCharging() {
	        this.$refs.extendDialog.open();
	      },
	      
	      onExtendChange(e) {
	        this.extendIndex = e.detail.value;
	      },
	      
	      cancelExtend() {
	        this.$refs.extendDialog.close();
	      },
	      
	      confirmExtend() {
	        // 发送延长充电请求
	        this.$refs.extendDialog.close();
	        uni.showToast({
	          title: `已延长${this.extendOptions[this.extendIndex]}`,
	          icon: 'success'
	        });
	      },
	      
	      // 显示帮助
	      showHelp() {
	        uni.navigateTo({
	          url: '/pages/help/chargingHelp'
	        });
	      },
	      
	      // 绘制功率曲线
	      drawPowerChart() {
	        // 这里应该是实际绘制图表的代码
	        console.log("绘制功率曲线图");
	      },
	      mounted() {
	          this.drawPowerChart();
	        },
    // 初始化WebSocket连接
    initWebSocket() {
      const url = `${this.$wsUrl}/ws/server/${this.userId}`;
      
      this.socketTask = uni.connectSocket({
        url: url,
        complete: () => {}
      });

      this.socketTask.onOpen(() => {
        console.log("WebSocket连接成功");
        this.isSocketConnected = true;
        this.reconnectCount = 0;
        this.startPing();
        this.sendChargingStart();
      });

      this.socketTask.onMessage((res) => {
        try {
          const data = JSON.parse(res.data);
          this.handleSocketMessage(data);
        } catch (e) {
          console.error("WebSocket消息解析错误", e);
        }
      });

      this.socketTask.onClose(() => {
        console.log("WebSocket连接关闭");
        this.isSocketConnected = false;
        this.handleReconnect();
      });

      this.socketTask.onError((err) => {
        console.error("WebSocket错误", err);
        this.isSocketConnected = false;
        this.handleReconnect();
      });
    },
    
    // 处理WebSocket消息
    handleSocketMessage(data) {
      switch(data.state) {
        case 1: // 异常通知
          this.showMessage('error', data.data);
          break;
        case 2: // 余额不足
          this.showBalanceAlert();
          break;
        case 3: // 充电进度更新
          this.updateChargingData(data.data);
          break;
        default:
          console.log("未知消息类型", data);
      }
    },
    
    // 更新充电数据
    updateChargingData(newData) {
      this.chargingProgress = {
        ...this.chargingProgress,
        chargingCapacity: parseFloat(newData.chargingCapacity) || 0,
        totalCapacity: parseFloat(newData.totalCapacity) || 1,
        oneElectricityCost: parseFloat(newData.oneElectricityCost) || 0,
        hours: parseInt(newData.hours) || 0,
        minutes: parseInt(newData.minutes) || 0,
        seconds: parseInt(newData.seconds) || 0,
        totalCost: parseFloat(newData.totalCost) || 0
      };
      
      this.isCharging = this.chargingProgress.chargingCapacity > 0 && 
                       this.chargingProgress.chargingCapacity < this.chargingProgress.totalCapacity;
    },
    
    // 发送充电开始消息
    sendChargingStart() {
      if (this.socketTask && this.isSocketConnected) {
        this.socketTask.send({
          data: JSON.stringify({
            type: "charging_start",
            billId: this.billId
          }),
          success: () => console.log("充电开始消息发送成功")
        });
      }
    },
    
    // 开始心跳检测
    startPing() {
      this.pingInterval = setInterval(() => {
        if (this.socketTask && this.isSocketConnected) {
          this.socketTask.send({
            data: "ping",
            success: () => {}
          });
        }
      }, 5000);
    },
    
    // 处理重连
    handleReconnect() {
      if (this.reconnectCount < 3 && this.isPageShow) {
        this.reconnectCount++;
        console.log(`尝试第${this.reconnectCount}次重连...`);
        setTimeout(() => {
          this.initWebSocket();
        }, 2000);
      } else {
        this.showMessage('error', '连接服务器失败，请返回重试');
      }
    },
    
    // 关闭WebSocket
    closeWebSocket() {
      if (this.socketTask) {
        this.socketTask.close();
      }
      if (this.pingInterval) {
        clearInterval(this.pingInterval);
        this.pingInterval = null;
      }
      this.isSocketConnected = false;
    },
    
    // 显示余额不足提示
    showBalanceAlert() {
      uni.showModal({
        title: '余额不足',
        content: '您的账户余额不足，请先充值',
        confirmText: '去充值',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/myWallet/myWallet'
            });
          }
        }
      });
    },
    
    // 显示消息弹窗
    showMessage(type, content) {
      this.msgType = type;
      this.messageText = content;
      this.$refs.alertDialog.open();
    },
    
    // 弹窗确认
    dialogConfirm() {
      // 可根据msgType处理不同的确认操作
    },
    
    // 弹窗关闭
    dialogClose() {
      // 弹窗关闭回调
    },
    
    // 结束充电
    stopCharging() {
      if (this.socketTask && this.isSocketConnected) {
        this.socketTask.send({
          data: JSON.stringify({
            type: "charging_stop",
            billId: this.billId
          }),
          success: () => {
            uni.navigateTo({
              url: `/pages/order-detail/order-detail?billId=${this.billId}`
            });
          }
        });
      } else {
        uni.navigateTo({
          url: `/pages/order-detail/order-detail?billId=${this.billId}`
        });
      }
    },
    
    // 清理资源
    cleanup() {
      this.closeWebSocket();
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    }
  }
}
</script>

<style>
.container {
  padding: 20rpx;
}

/* 进度条容器 */
.progress-wrapper {
  display: flex;
  justify-content: center;
  margin: 40rpx 0;
}

/* 环形进度条 */
.progress-circle {
  width: 300rpx;
  height: 300rpx;
  position: relative;
}

/* 进度条背景（灰色圆环） */
.progress-background {
  width: 100%;
  height: 100%;
  border: 16rpx solid #f0f0f0;
  border-radius: 50%;
  box-sizing: border-box;
  position: absolute;
}

/* 进度条填充（蓝色部分） */
.progress-fill {
  width: 100%;
  height: 100%;
  border: 16rpx solid transparent;
  border-top-color: #0091FF;
  border-right-color: #0091FF;
  border-radius: 50%;
  box-sizing: border-box;
  position: absolute;
  transform: rotate(-90deg);
  transform-origin: center;
  transition: transform 0.5s ease;
}

/* 百分比文字 */
.progress-percent {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 36rpx;
  color: #333;
  z-index: 2;
}

/* 充电信息区域 */
.charging-info {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-top: 40rpx;
  padding: 20rpx 0;
  background-color: #f9f9f9;
  border-radius: 16rpx;
}

.info-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.info-label {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.info-value {
  font-size: 28rpx;
  color: #0091FF;
  font-weight: bold;
}

.divider {
  width: 1px;
  height: 40rpx;
  background-color: #eee;
}

/* 结束充电按钮 */
.stop-button {
  background-color: #0091FF;
  color: white;
  margin: 40rpx 30rpx;
  border-radius: 50rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
}

.stop-button:active {
  opacity: 0.8;
}
.container {
  padding: 20rpx;
  padding-bottom: 40rpx;
}

/* 充电站信息 */
.station-info {
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
  margin-bottom: 20rpx;
}

.station-header {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.station-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 15rpx;
}

.station-name {
  font-size: 32rpx;
  font-weight: bold;
  flex: 1;
}

.station-status {
  font-size: 24rpx;
  color: #fff;
  background-color: #FF5B5B;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.station-status.available {
  background-color: #09BB07;
}

.station-detail {
  display: flex;
  justify-content: space-between;
  font-size: 24rpx;
  color: #666;
}

.station-address {
  flex: 1;
}

.station-distance {
  margin-left: 20rpx;
  color: #0091FF;
}

/* 信息卡片 */
.info-card {
  background-color: #f9f9f9;
  border-radius: 12rpx;
  padding: 20rpx;
  margin: 30rpx 0;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15rpx;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  color: #666;
  font-size: 26rpx;
}

.info-value {
  color: #333;
  font-size: 26rpx;
  font-weight: bold;
}

/* 统计网格 */
.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
  margin: 30rpx 0;
}

.stat-item {
  background-color: #f5f7fa;
  border-radius: 12rpx;
  padding: 20rpx;
  text-align: center;
}

.stat-value {
  font-size: 32rpx;
  color: #0091FF;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}

/* 图表区域 */
.chart-container {
  margin-top: 40rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 20rpx;
}

.chart {
  width: 100%;
  height: 300rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
}

/* 操作按钮组 */
.action-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 40rpx;
  padding: 0 20rpx;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 30%;
  height: 140rpx;
  border-radius: 12rpx;
  font-size: 24rpx;
  background-color: #fff;
  border: 1rpx solid #eee;
}

.action-btn text {
  margin-top: 10rpx;
}

.btn-icon {
  width: 50rpx;
  height: 50rpx;
}

.extend-btn {
  color: #FF9500;
  border-color: #FF9500;
}

.stop-btn {
  color: #FF5B5B;
  border-color: #FF5B5B;
}

.help-btn {
  color: #0091FF;
  border-color: #0091FF;
}

/* 延长充电弹窗 */
.extend-dialog {
  padding: 40rpx;
  background-color: #fff;
  border-radius: 16rpx;
}

.dialog-title {
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
  display: block;
}

.picker {
  padding: 20rpx;
  background-color: #f5f7fa;
  border-radius: 8rpx;
  margin-bottom: 40rpx;
  text-align: center;
}

.dialog-buttons {
  display: flex;
  justify-content: space-between;
}

.dialog-btn {
  width: 48%;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.cancel {
  background-color: #f5f7fa;
  color: #666;
}

.confirm {
  background-color: #0091FF;
  color: #fff;
}

/* 原有样式... */
.progress-wrapper {
  margin: 20rpx 0 40rpx;
}

.progress-circle {
  width: 280rpx;
  height: 280rpx;
}

.progress-background {
  border-width: 12rpx;
}

.progress-fill {
  border-width: 12rpx;
}

.progress-percent {
  font-size: 32rpx;
}
</style>